/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {StyleSheet, Text, View, BackHandler, DeviceEventEmitter, PixelRatio, Platform, ScrollView, Dimensions, Image, TouchableOpacity, TouchableHighlight, TouchableNativeFeedback, Modal} from 'react-native';

import Common from '../../component/common';

import ToolbarComponent from '../../component/ToolbarComponent';

import MediaBar from './mediaBar';

import MediaData from './mediaData';

import AnalysisPos from './analysisPos';

import AnalysisNeg from './analysisNeg';

import VarietyDetail from './varietyDetail';

import MovieDetail from './movieDetail';

import TVDetail from './TVDetail';

import NewsGroup from './newsGroup';

import Share from '../../component/share';

import LoadError from '../../component/loadError';

import Loading from '../../component/loading';

import IndustryMedia from './industryMedia';

import AllMedia from './allMedia';
import ScreenUtils from '../../component/ScreenUtils';

const os = Platform.OS;

const totalWidth = Dimensions.get('window').width;

export default class Detail extends Component {
  constructor(props) {
    super(props);
    this.state = {
      source: {},
      flag: false,
      loading: true,
      success: false,
      errorMessage: '',
      modalVisible: false,
      isCollection: false,
      isIndustryMedia: true,
      isPos: true,
      checkDevice: '',
    };
  }
  componentWillMount(){
    Common.checkDevice((checkDevice) => {
      this.setState({checkDevice});
    });
    if (os === 'android') {
      this.hardsare = BackHandler.addEventListener('hardwareBackPress', () => {
        // DeviceEventEmitter.emit("refreshBillboard",null);
        Common.onBack(this,{"id":this.props.did,"type":this.props.name,"collectionStatus":this.collection == this.state.isCollection});
        return true;
      });
    }
  }
  componentDidMount() {
    this.fetchDetailData();
  }
  componentWillUnmount() {
    if (os === 'android') {
      BackHandler.removeEventListener('hardwareBackPress', () => Common.onBack(this,{"id":this.props.did,"type":this.props.name,"collectionStatus":this.collection == this.state.isCollection}));
    }
  }
  fetchDetailData = () => {
    this.setState({
      loading: true,
      success: false,
    });
    this.timer = setTimeout(() => {
      let formData = new FormData();
      formData.append("id", this.props.did);
      formData.append("type", this.props.name);
      formData.append("ranking",this.props.parentId || 5);
      Common.fetchData("post", "/billboard/detail", formData, (responseData) => {
        var source = Object.assign({}, responseData.result,{mmCurrentReportCount:responseData.mmCurrentReportCount,
                                                            mmYesterdayReportCount:responseData.mmYesterdayReportCount
                                                          })
        this.setState({
          source: source,
          flag: true,
          loading: false,
          success: true,
        });
      },() => {
        this.setState({loading: false,
                        success: false,
                        errorMessage: "请求失败",
                      });
      },() => {
        this.setState({loading: false,
                        success: false,
                        errorMessage: "网络错误",
                      });
      });
      Common.isCollection({id:this.props.did, type: this.props.name}, () => {
        this.setState({isCollection: true});
        this.collection = true;
      }, () => {
        this.setState({isCollection: false});
        this.collection = false;
      });
      clearTimeout(this.timer);
    },1000);
  };
  onMediaSwitch = (isIndustryMedia) => {
    this.setState({isIndustryMedia});
  };
  onAnalysisSwitch = (isPos) => {
    this.setState({isPos});
  };
  updown = (data) =>{
    var updown = {};
    if(data > 0){
      updown.change = data;
      updown.icon = require('../../images/up.png');
    }else if(data < 0){
      updown.change = -data;
      updown.icon = require('../../images/down.png');
    }else{
      updown.change = "";
      updown.icon = require('../../images/still.png');
    }
    return updown;
  };
  isShow = () => {
    var flag = this.state.modalVisible?false:true;
    this.setState({modalVisible: flag});
  };
  render() {
    var updown = this.updown(this.state.source.rankingChanged);
    var collectionIcon = this.state.isCollection?require("../../images/collection/Collectionon.png"):require("../../images/collection/Collectionoff.png");
    var type = "历史";
    switch (this.props.parentId){
      case 1:
        type = "8小时";
        break;
      case 2:
        type = "24小时";
        break;
      case 3:
        type = "7日";
        break;
      case 4:
        type = "月度";
        break;
      case 5:
        type = "历史";
        break;
      default:
        type = "历史排名";
        break;
    }
    return (
      <View style={{flex: 1}}>
        <ToolbarComponent
          leftItem={{
            title: 'Back',
            layout: 'icon',
            icon: require("../../images/back.png"),
            onPress: () => {
              Common.onBack(this,{"id":this.props.did,"type":this.props.name,"collectionStatus":this.collection == this.state.isCollection});
              // DeviceEventEmitter.emit("refreshBillboard",null);
            },
          }}
          extraItem={{
            title: 'Collection',
            layout: 'icon',
            icon: collectionIcon,
            onPress: () => {
              if(this.state.isCollection){
                Common.deleteCollection({id: this.props.did, type: this.state.source.type},() => {
                  this.setState({isCollection: false});
                });
              }else{
                Common.addCollection({id: this.props.did, type: this.state.source.type},() => {
                  this.setState({isCollection: true});
                });
              }
            },
          }}
          rightItem={{
            title: 'Share',
            layout: 'icon',
            icon: require("../../images/share/share.png"),
            onPress: () => {
              if(this.refs.share){
                this.refs.share.show(this.location, this.state.source.id,false);
              }
            },
          }}
        >
          <View style={styles.toolbarV}>
            <Text style={styles.toolbarT} numberOfLines={1}>详情</Text>
          </View>
        </ToolbarComponent>
        {
          (this.state.loading?
            <Loading />:
            (this.state.success?
            <View style={{flex:1}}>
              <ScrollView removeClippedSubviews={false} enableEmptySections={true} style={styles.container}>
                <View ref={(e) => this.location = e} style={styles.backgroundColor}>
                  <View style={styles.dealMargin}>
                   
                      {this.props.name == 1?
                        <VarietyDetail program={this.state.source} />:null
                      }
                      {this.props.name == 2?
                        <MovieDetail program={this.state.source} />:null
                      }
                      {this.props.name == 3?
                        <TVDetail program={this.state.source} />:null
                      }
                      {this.props.name == 4?
                        <NewsGroup program={this.state.source} />:null
                      }
                      <View style={styles.programA}>
                        <TouchableHighlight underlayColor="transparent" onPress={() => this.isShow()}>
                          <View style={styles.reportA}>
                            <Text style={styles.reportTime}>{type}</Text>
                            <Text style={styles.reportT}>报道指数</Text>
                            <Image style={styles.reportIcon} source={require('../../images/home/question_mark.png')} />
                            {/*<View style={styles.reportIcon}>
                              <Text style={styles.reportIconT}>?</Text>
                            </View>*/}
                          </View>
                        </TouchableHighlight>
                        <View style={styles.reportN}>
                          <Text>
                            <Text style={styles.reportNT}>{String (this.state.source.indexNumber || 0)}</Text>
                            <Text style={{fontSize: 12,color: '#ff4849',textAlignVertical: 'bottom'}}>/10</Text>
                          </Text>
                        </View>
                        <View style={styles.reportRankA}>
                          <Text style={styles.reportRankAT}>排名{String (this.state.source.ranking || 0)}</Text>
                          <View style={styles.reportChange}>
                            <Image style={styles.reportChangeI} source={updown.icon} />
                            <Text style={styles.reportChangeN}>{String (updown.change || 0)}</Text>
                          </View>
                        </View>
                      </View>
                    
                  </View>

                  <View style={styles.dealMargin}>
                    <View style={styles.mediaTitle}> 
                      <TouchableOpacity style={styles.mediaTitlePart} onPress={() => this.onMediaSwitch(true)}>
                        <View style={styles.mediaTitlePartW}>
                          <Text style={[styles.mediaTitlePartT,{color: this.state.isIndustryMedia?'#fff':'#ffc4c6'}]}>媒体监测库</Text>
                        </View>
                        <View style={[styles.mediaTitlePartTLine,{backgroundColor: this.state.isIndustryMedia?'#fff':'#ff5757'}]}></View>
                      </TouchableOpacity>
                      <TouchableOpacity style={[styles.mediaTitlePart,{}]} onPress={() => this.onMediaSwitch(false)}>
                        <View style={styles.mediaTitlePartW}>
                          <Text style={[styles.mediaTitlePartT,{color: this.state.isIndustryMedia?'#ffc4c6':'#fff'}]}>全网媒体</Text>
                        </View>
                        <View style={[styles.mediaTitlePartTLine,{backgroundColor: this.state.isIndustryMedia?'#ff5757':'#fff'}]}></View>
                      </TouchableOpacity>
                    </View>
                    {
                      this.state.isIndustryMedia?
                      <IndustryMedia data={this.state.source} {...this.props}/>:
                      <AllMedia data={this.state.source}/>
                    }
                  </View>
                  {
                    this.state.source.negNewsList && this.state.source.negNewsList.length || this.state.source.posNewsList && this.state.source.posNewsList.length?
                      <View style={styles.dealMargin}>
                        <View style={styles.mediaTitle}> 
                          <TouchableOpacity style={[styles.mediaTitlePart,{}]} onPress={() => this.onAnalysisSwitch(true)}>
                            <View style={styles.mediaTitlePartW}>
                              <Text style={[styles.mediaTitlePartT,{color: this.state.isPos?'#fff':'#ffc4c6'}]}>正面舆情</Text>
                            </View>
                            <View style={[styles.mediaTitlePartTLine,{backgroundColor: this.state.isPos?'#fff':'#ff5757'}]}></View>
                          </TouchableOpacity>
                          <TouchableOpacity style={[styles.mediaTitlePart,{}]} onPress={() => this.onAnalysisSwitch(false)}>
                            <View style={styles.mediaTitlePartW}>
                              <Text style={[styles.mediaTitlePartT,{color: this.state.isPos?'#ffc4c6':'#fff'}]}>负面舆情</Text>
                            </View>
                            <View style={[styles.mediaTitlePartTLine,{backgroundColor: this.state.isPos?'#ff5757':'#fff'}]}></View>
                          </TouchableOpacity>
                        </View>
                        {
                          this.state.isPos?
                            <AnalysisPos data={this.state.source} {...this.props}/>:
                            <AnalysisNeg data={this.state.source} {...this.props}/>
                        }
                      </View>:null
                  }
                  {
                    this.state.source.playCountDisplay?
                      <View style={styles.dealMargin}>
                      <View style={styles.mediaData}>
                        <MediaData data={this.state.source} />
                        <MediaBar data={this.state.source} />
                      </View></View>:null
                  }
                </View>
              </ScrollView>
              <Share ref="share" />
            </View>
              :
              <LoadError reload={this.fetchDetailData} reason={this.state.errorMessage}/>))
        }
                <Modal animationType={"fade"}
                  transparent={true}
                  visible={this.state.modalVisible}
                  onRequestClose={this.isShow}>
                  <TouchableOpacity style={styles.mask} onPress={this.isShow}>
                    <TouchableOpacity style={styles.tipBox} activeOpacity={1}>
                    <View>
                      <View style={styles.tipTitle}>
                       <Image style={styles.tipTitleI} source={require('../../images/home/question_mark_d.png')} />
                        {/*<View style={styles.tipTitleI}>
                          <Text style={styles.tipTitleIT}>?</Text>
                        </View>*/}
                        <Text style={styles.tipTitleT}>指标说明</Text>
                      </View>
                      <View style={styles.tipContent}>
                        <View style={styles.tipCon}>
                          <Text style={styles.tipConL}>报道指数：</Text>
                          <Text style={styles.tipConR}>行业媒体分为五个等级，每个等级权值不同；报道指数=[(该行业媒体权值*报道数量)/该等级行业媒体数量]总和。</Text>
                        </View>
                        <View style={styles.tipCon}>
                          <Text style={styles.tipConL}>舆情分析：</Text>
                          <Text style={styles.tipConR}>通过对主流媒体的报道内容智能分析，识别出媒体的情感意见，以图表时间轴形式动态展示正负面评论，并显示最具特色的评论内容。</Text>
                        </View>
                      </View>
                      </View>
                    </TouchableOpacity>
                  </TouchableOpacity>
                </Modal>
              </View>
    );
  }
}

const styles = StyleSheet.create({ 
  container: {
    flex: 1,
    backgroundColor: '#f2f2f2',
  },
  backgroundColor: {backgroundColor: '#f2f2f2'},
  page: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  toolbarV: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  toolbarT: {
    color: '#ffffff',
    fontWeight: 'bold',
    fontSize: 20
  },
  mediaData: {
    /*marginTop: totalWidth*0.032,*/
    flexDirection: 'row',
    backgroundColor: '#fff',
    marginBottom: totalWidth*0.064,
  },
  programA: {
    width: totalWidth*0.22,
    position: 'absolute',
    right: totalWidth*0.04,
    bottom: totalWidth*0.077,
    backgroundColor: 'transparent',
    justifyContent: 'space-between',
  },
  reportA: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'flex-end',
  },
  reportTime: {
    color: 'rgba(254,70,70,0.3)',
    fontSize: 9,
    marginRight: 4,
  },
  reportT: {
    color: '#d7d7d7',
    fontSize: 9,
  },
  reportI: {
    width: totalWidth*0.037,
    height: totalWidth*0.037,
  },
  reportIcon: {
    width: totalWidth*0.023,
    height: totalWidth*0.023,
    resizeMode: 'contain',
    justifyContent: 'center',
    alignItems: 'center',
  },
  reportIconT: {
    color: '#ffffff',
    fontSize: 10,
    fontWeight: 'bold'
  },
  reportN: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'flex-end',
    justifyContent: 'flex-end',
    borderBottomColor: '#ff4849',
    borderBottomWidth: 1/PixelRatio.get(),
    marginTop: totalWidth*0.022,
    marginBottom: totalWidth*0.01,
  },
  reportNT: {
    fontSize: 38,
    color: '#ff4849',
  },
  reportRankA: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
  },
  reportRankAT: {
    color: '#ff4849',
    fontSize: 10,
    marginRight: 7,
  },
  reportChange: {
    flexDirection: 'row',
    alignItems: 'flex-end',
  },
  reportChangeI:{
    width: totalWidth*0.023,
    height: totalWidth*0.023,
    resizeMode: 'contain',
    marginBottom: totalWidth*0.005
  },
  reportChangeN: {
    color: '#ff4849',
    fontSize: 10,
  },
  mediaTitle: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#ff5757',
    borderTopLeftRadius:5,
    borderTopRightRadius:5,
    display:'flex',
    width: totalWidth-2*ScreenUtils.scaleSize(10),
  },
  mediaTitlePart: {
    flex: 1,
    height: Math.round(totalWidth*0.1),
    justifyContent: 'center',
    alignItems: 'center',
  },
  mediaTitlePartW: {
    height: Math.round(totalWidth*0.1)-2,
    justifyContent: 'center',
  },
  mediaTitlePartT: {
    color: '#fff',
    fontSize: 16,
  },
  mediaTitlePartTLine: {
    width: totalWidth*0.16,height: 2,backgroundColor: 'white',
  },
  mask: {
    flex: 1,
    backgroundColor:'rgba(0, 0, 0, 0.5)', 
    justifyContent: 'center',
    alignItems: 'center',
  },
  tipBox: {
    paddingBottom: totalWidth*0.037,
    backgroundColor: '#fff',
    borderRadius: 5,
  },
  tipTitle: { 
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: totalWidth*0.03,
    paddingBottom: totalWidth*0.005,
  },
  tipTitleI: {
    width: totalWidth*0.04,
    height: totalWidth*0.04,
    resizeMode: 'contain',
    marginRight: 2,
  },
  tipTitleIT: {
    color: '#fff',
    fontSize: 12,
  },
  tipTitleT: {
    color: '#000',
    fontWeight: 'bold',
    fontSize: 13,
  },
  tipCon: {
    width: totalWidth*0.8,
    flexDirection: 'row',
    paddingHorizontal: totalWidth*0.037,
    paddingVertical: 2,
  },
  tipConL: {
    flex: 2,
    color: '#ff4546',
    lineHeight: Math.round(totalWidth*0.05),
    fontSize: 11,
  },
  tipConR: {
    flex: 7,
    color: '#000',
    lineHeight: Math.round(totalWidth*0.05),
    fontSize: 11,
  },
  //新添
  dealMargin: {
    margin:ScreenUtils.scaleSize(10),
    backgroundColor: '#fff',
    borderRadius: 5,

  }
});